package org.example.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Base64;
import java.util.Date;

/**
 * @author Rommel
 * @version 1.0
 * @date 2023/6/18-21:09
 * @description TODO
 */
public class JwtUtils {

    public static String base64EncodedSecretKey = Base64.getEncoder().encodeToString("jwt-secret".getBytes());

    /**
     *
     * @param id
     * @param sub
     * @param exp
     * @param alg
     * @param secretKey
     * @return
     * @author  Rommel
     * @date    2023/6/18-21:15
     * @version 1.0
     * @description  创建jwt
     */
    public static String createJwt(String id,String sub,Date exp,SignatureAlgorithm alg,String secretKey){

        String jwt = Jwts.builder()
                .setId(id)
                .setSubject(sub)
                //有效期两小时
                .setExpiration(exp)
                //采用什么算法是可以自己选择的，不一定非要采用HS512
                .signWith(alg, secretKey)
                .compact();

        return jwt;
    }

    /**
     *
     * @param jwt
     * @param secretKey
     * @return
     * @author  Rommel
     * @date    2023/6/18-21:25
     * @version 1.0
     * @description  解析jwt-token
     */
    public static Claims parseJwt(String jwt, String secretKey){
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt).getBody();
    }


}
